from django import forms
from django.core import exceptions
from django.contrib.contenttypes.models import ContentType
from ckeditor.widgets import CKEditorWidget

from .models import Comment

class CommentForm(forms.Form):
    content_type = forms.CharField(widget=forms.HiddenInput)
    object_id = forms.IntegerField(widget=forms.HiddenInput)
    text = forms.CharField(widget=CKEditorWidget(config_name='comment_config'), error_messages={'required':'评论不能为空'})
    # 所回复的评论主键
    reply_comment_pk = forms.IntegerField(widget=forms.HiddenInput)

    def __init__(self, *args, **kwargs):
        if 'user' in kwargs:
            self.user = kwargs.pop('user')
        super(CommentForm, self).__init__(*args, **kwargs)
    
    def clean_reply_comment_pk(self):
        reply_comment_pk = self.cleaned_data['reply_comment_pk']
        if reply_comment_pk < 0:
            raise forms.ValidationError('评论错误', code='ObjectDoesNotExist')
        elif reply_comment_pk == 0:
            self.cleaned_data['parent'] = None
        elif Comment.objects.filter(pk=reply_comment_pk).exists():
            self.cleaned_data['parent'] = Comment.objects.get(pk=reply_comment_pk)
        else:
            raise forms.ValidationError('评论错误', code='ObjectDoesNotExist')

    def clean(self):
        # 获取评论对象
        try:
            model_ct = ContentType.objects.get(model=self.cleaned_data['content_type'])
            model_obj = model_ct.get_object_for_this_type(pk=self.cleaned_data['object_id'])
            self.cleaned_data['model_obj'] = model_obj
        except exceptions.ObjectDoesNotExist:
            raise forms.ValidationError('对象不存在', code='ObjectDoesNotExist') 

        # 验证用户信息
        if self.user.is_authenticated:
            self.cleaned_data['user'] = self.user
        else:
            raise forms.ValidationError('用户未登录', code='UserDoesNotLogin')

        return self.cleaned_data